package com.schoolCommunity.community.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.schoolCommunity.community.entity.DTO.LoginParam;
import com.schoolCommunity.community.entity.User;
import com.schoolCommunity.community.entity.common.Result;
import com.schoolCommunity.community.mapper.UserMapper;
import com.schoolCommunity.community.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.schoolCommunity.community.utils.JwtUtil;
import io.jsonwebtoken.JwtBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liuhongbin
 * @since 2023-12-14
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Result login(LoginParam loginParam) {
       if (BeanUtil.isEmpty(loginParam)){
           return Result.error("账号与密码不能为空",4011,null);
       }

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
       userQueryWrapper.eq("account",loginParam.getAccount());
        User one = this.getOne(userQueryWrapper);

        if (BeanUtil.isEmpty(one) ||!one.getPassword().equals(loginParam.getPassword())){
            return Result.error("账号或密码输入错误",4012,null);
        }

        //要加密再补

        String userid = one.getId().toString();
        String token = JwtUtil.createJWT(userid);

        one.setAccount(null);
        one.setPassword(null);
        redisTemplate.opsForValue().set("login:"+userid,one);

        return Result.success("成功登录",200,token);
    }
}
